/**
 * 
 */
package com.hls;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author huangliusong 
 * E-mail:huangliusong1994@gmail.com
 * @version 创建时间：2018年7月10日 上午11:06:50
 */
public class ExeLinuxCommand {
	public static void main(String[] args) {
		judge(args);
	}

	public static void judge(String[] args) {
		if (args.length == 0) {
			System.err
					.println("---------------------------------------------------");
			System.err.println("your args err!");
			System.err.println("Use Method:first args is shell filename");
			System.err.println("Use Method:second args is shell param");
			System.err
					.println("example:java -jar abc.jar test.sh 'select * from hls'");
			System.err
					.println("---------------------------------------------------");

		} else {
			exeShell(args);
		}
	}

	public static String exeShell(String[] args) {
		String[] commands = null;
		if (args.length == 1) {
			commands = new String[] { args[0] };
		} else if (args.length == 2) {
			commands = new String[] { args[0], args[1] };
		} else if (args.length == 3) {
			commands = new String[] { args[0], args[1], args[2] };
		} else if (args.length == 4) {
			commands = new String[] { args[0], args[1], args[2], args[3] };
		} else if (args.length == 5) {
			commands = new String[] { args[0], args[1], args[2], args[3],
					args[4] };
		} else {
			return "huangliusong tell you:can't surport you args";
		}
		String result = null;
		Process process = null;
		Runtime runTime = Runtime.getRuntime();
		try {
			// "sh a.sh 1 2 3"
			process = runTime.exec(commands);
			process.waitFor();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line).append("\n");
			}
			result = sb.toString();
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
